package controller

import (
	"github.com/gin-gonic/gin"
	"shop-bean/constant"
	"shop-bean/model"
	"shop-bean/request"
	"shop-common/library/serializer"
	"shop-service/business"
)

type ShopCartController struct{}

// @Tags 购物车接口
// @description: 获取用户购物车信息
// @Summary 获取用户购物车信息，参数为用户选中的活动项数组,以购物车id为key
// @Security ApiKeyAuth
// @function: AddItem
// @Accept  json
// @Produce  json
// @Param data body request.ChangeShopCartRequest true "加入购物车参数"
// @Success 200 {object} string "{"code":1," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /shopCart/changeItem [post]
func (c *ShopCartController) AddItem(ctx *gin.Context) {
	//todo 乐观锁
	form := request.ChangeShopCartRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	userId := StaticUserId

	shopCartItems, err := business.ServiceImpl().BasketService.FindByUserIdShopCart(ctx, userId)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicUpdateErr)
		return
	}

	prodParam, err := business.ServiceImpl().ProductService.FindById(form.ProdId)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicUpdateErr)
		return
	}

	skuParam, err := business.ServiceImpl().ProductService.FindBySkuId(ctx, form.SkuId)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicUpdateErr)
		return
	}

	// 当商品状态不正常时，不能添加到购物车
	if prodParam.Status != constant.GLOBAL_ENABLE || skuParam.Status != constant.GLOBAL_ENABLE {
		serializer.Fail(ctx, "当前商品已下架")
		return
	}

	for _, shopCartItemDto := range shopCartItems {
		if form.SkuId == shopCartItemDto.ShopId {
			basket := &model.Basket{
				BasketId:    shopCartItemDto.BasketId,
				UserId:      userId,
				BasketCount: form.Count + shopCartItemDto.ProdCount,
			}

			// 防止购物车变成负数
			if basket.BasketCount <= 0 {
				_ = business.ServiceImpl().BasketService.DeleteBatchByBasketIds(ctx, userId, []uint{form.BasketId})
				serializer.Success(ctx, "")
				return
			}

			// 当sku实际库存不足时，不能添加到购物车
			if skuParam.Stocks < basket.BasketCount && shopCartItemDto.ProdCount > 0 {
				// 库存不足
				serializer.Fail(ctx, serializer.PublicUpdateErr)
				return
			}

			_ = business.ServiceImpl().BasketService.Updates(ctx, basket)
			serializer.Success(ctx, "")
		}
	}

	// 防止购物车已被删除的情况下,添加了负数的商品
	if form.Count < 0 {
		serializer.Fail(ctx, "商品已从购物车移除")
		return
	}

	// 当sku实际库存不足时，不能添加到购物车
	if skuParam.Stocks < form.Count {
		serializer.Fail(ctx, "库存不足")
		return
	}

	// 所有都正常时
	err = business.ServiceImpl().BasketService.Create(ctx, &form, userId)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicUpdateErr)
		return
	}
	serializer.Success(ctx, serializer.PublicCreateSuccess)
}

// @Tags 购物车接口
// @description: 添加、修改用户购物车物品
// @Summary 通过商品id(prodId)、skuId、店铺Id(shopId),添加/修改用户购物车商品，并传入改变的商品个数(count),当count为正值时，增加商品数量，当count为负值时，将减去商品的数量，当最终count值小于0时，会将商品从购物车里面删除
// @Security ApiKeyAuth
// @function: Info
// @Accept  json
// @Produce  json

// @Success 200 {object} string "{"code":1," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /shopCart/info [get]
func (c *ShopCartController) Info(ctx *gin.Context) {
	// 更新购物车信息，

	// 拿到购物车的所有item
	shopCartItems, err := business.ServiceImpl().BasketService.FindByUserIdShopCart(ctx, StaticUserId)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicQueryErr)
		return
	}

	serializer.SuccessData(ctx, "", shopCartItems)

}

// @Tags 购物车接口
// @description: 删除用户购物车物品
// @Summary 通过购物车id删除用户购物车物品
// @Security ApiKeyAuth
// @function: DeleteItem
// @Accept  json
// @Produce  json
// @Param data body request.CommonBatchRequest true "请求参数"
// @Success 200 {object} string "{"code":1," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /shopCart/deleteItem [delete]
func (c *ShopCartController) DeleteItem(ctx *gin.Context) {
	form := request.CommonBatchRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	err := business.ServiceImpl().BasketService.DeleteBatchByBasketIds(ctx, StaticUserId, form.Ids)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicDeleteErr)
		return
	}

	serializer.Success(ctx, "")
}

// @Tags 购物车接口
// @description: 清空用户购物车所有物品
// @Summary 清空用户购物车所有物品
// @Security ApiKeyAuth
// @function: DeleteAll
// @Accept  json
// @Produce  json
// @Success 200 {object} string "{"code":1," result":{}, "message":"操作成功", "time":1618493448}"
// @Router /shopCart/deleteAll [delete]
func (c *ShopCartController) DeleteAll(ctx *gin.Context) {
	form := request.CommonBatchRequest{}
	if err := serializer.Verify(ctx, &form); err != nil {
		serializer.Fail(ctx, err.Error())
		return
	}

	err := business.ServiceImpl().BasketService.DeleteBatchByBasketIds(ctx, StaticUserId, form.Ids)
	if err != nil {
		serializer.Fail(ctx, serializer.PublicDeleteErr)
		return
	}

	serializer.Success(ctx, "")
}
